package server;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;

public class RequestProcessor extends Thread {


    private Socket socket;
    private Service service;
    public RequestProcessor(Socket socket, Service service) {
        this.socket = socket;
        this.service = service;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());


            String url = request.getUrl();
            Host host = service.getHost();
            response.setAppBase(host.getAppBase());

            // 不是当前host不处理
            if (!host.getName().equals(request.getHost())) {
                response.output(HttpProtocolUtil.getHttpHeader404());
            }
            List<Context> contextList = host.getContextList();


            // 判断属于哪个context 需要解读所有context
            Context currentContext = null;
            Wrapper currentWrapper = null;
            for (Context context : contextList) {
                HashMap<String, Wrapper> wapperMap = context.getWapperMap();
                String prefix = "/" + context.getName();
                if (url.startsWith(prefix)) {
                    // 获取匹配的context
                    currentContext = context;
                    // 修改url为相对路径
                    url = url.replace(prefix, "");
                    currentWrapper = wapperMap.get(url);
                    break;
                }
            }
            // 没有匹配的context输出404
            if (currentContext == null) {
                response.outputHtml(request.getUrl());
                return;
            }

            // 主页
            if ("/".equals(url)) {
                response.outputHtml("/" + currentContext.getName() + "/index.html");
            }
            // 静态资源处理
            if(currentWrapper == null) {
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = currentWrapper.getServlet();
                System.out.println(httpServlet);
                httpServlet.service(request,response);
            }

        }catch (Exception e) {
            e.printStackTrace();

        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
